<template>
  <div class="tech-category-container">
    <el-card>

      <div class="category-grid">
        <!-- 现有技术方向卡片 -->
        <el-card
          v-for="category in techCategories"
          :key="category.id"
          class="category-card"
          :class="{ 'card-disabled': !category.isActive }"
          shadow="hover"
          @click="viewKnowledgePoints(category)"
        >
          <div class="card-content">
            <div class="card-icon" :style="{ color: category.color }">
              {{ category.icon }}
            </div>
            
            <div class="card-info">
              <h3 class="category-title">{{ category.categoryName }}</h3>
              <p class="category-desc">{{ category.description }}</p>
              
              <div class="category-meta">
                <el-tag :type="getDifficultyTagType(category.difficultyLevel)" size="small">
                  {{ getDifficultyText(category.difficultyLevel) }}
                </el-tag>
                <el-tag type="info" size="small" v-if="category.estimatedDuration">
                  {{ category.estimatedDuration }}
                </el-tag>
                <el-tag :type="category.isActive ? 'success' : 'danger'" size="small">
                  {{ category.isActive ? '启用' : '禁用' }}
                </el-tag>
              </div>
            </div>

            <div class="card-actions" @click.stop>
              <el-button
                type="primary"
                size="small"
                text
                @click="editCategory(category)"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button
                :type="category.isActive ? 'warning' : 'success'"
                size="small"
                text
                @click="toggleStatus(category)"
              >
                <el-icon><Switch /></el-icon>
                {{ category.isActive ? '禁用' : '启用' }}
              </el-button>
              <el-button
                type="danger"
                size="small"
                text
                @click="deleteCategory(category)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </div>
        </el-card>

        <!-- 添加新技术方向卡片 -->
        <el-card class="category-card add-card" shadow="hover" @click="addNewCategory">
          <div class="add-card-content">
            <el-icon class="add-icon" size="40">
              <Plus />
            </el-icon>
            <h3>添加技术方向</h3>
            <p>点击创建新的技术方向</p>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 编辑/添加技术方向对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑技术方向' : '添加技术方向'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="categoryForm"
        :rules="formRules"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="方向标识" prop="categoryKey">
          <el-input
            v-model="categoryForm.categoryKey"
            placeholder="请输入技术方向唯一标识"
            :disabled="isEdit"
          />
        </el-form-item>

        <el-form-item label="方向名称" prop="categoryName">
          <el-input
            v-model="categoryForm.categoryName"
            placeholder="请输入技术方向名称"
          />
        </el-form-item>

        <el-form-item label="图标" prop="icon">
          <el-input
            v-model="categoryForm.icon"
            placeholder="请输入emoji或图标"
          />
          <div class="icon-preview" v-if="categoryForm.icon">
            预览: <span :style="{ fontSize: '24px' }">{{ categoryForm.icon }}</span>
          </div>
        </el-form-item>

        <el-form-item label="主题色彩" prop="color">
          <el-color-picker v-model="categoryForm.color" />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入技术方向描述"
          />
        </el-form-item>

        <el-form-item label="难度级别" prop="difficultyLevel">
          <el-select v-model="categoryForm.difficultyLevel" placeholder="请选择难度级别">
            <el-option label="初学者" value="beginner" />
            <el-option label="中级" value="intermediate" />
            <el-option label="高级" value="advanced" />
          </el-select>
        </el-form-item>

        <el-form-item label="预计时长" prop="estimatedDuration">
          <el-input
            v-model="categoryForm.estimatedDuration"
            placeholder="如：3-6个月"
          />
        </el-form-item>

        <el-form-item label="排序号" prop="orderNum">
          <el-input-number
            v-model="categoryForm.orderNum"
            :min="0"
            :step="1"
          />
        </el-form-item>

        <el-form-item label="状态" prop="isActive">
          <el-switch
            v-model="categoryForm.isActive"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Switch, Refresh } from '@element-plus/icons-vue'
import router from '@/router'
import { get,post,put } from '@/axios'

// 响应式数据
const techCategories = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref(null)

// 表单数据
const categoryForm = reactive({
  id: null,
  categoryKey: '',
  categoryName: '',
  icon: '',
  color: '#409eff',
  description: '',
  difficultyLevel: 'beginner',
  estimatedDuration: '',
  orderNum: 0,
  isActive: 1,
  isDeleted: 0
})

// 表单验证规则
const formRules = {
  categoryKey: [
    { required: true, message: '请输入技术方向标识', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  categoryName: [
    { required: true, message: '请输入技术方向名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  difficultyLevel: [
    { required: true, message: '请选择难度级别', trigger: 'change' }
  ]
}

//获取表中信息
fetchTechCategories()
function fetchTechCategories(){
    get('/umsAdmin/getAllCategories',{},content=>{
      techCategories.value = content.filter(item=> item.isDeleted === 0)
    })
}

// 方法
const getDifficultyTagType = (level) => {
  const types = {
    'beginner': 'success',
    'intermediate': 'warning',
    'advanced': 'danger'
  }
  return types[level] || 'info'
}

const getDifficultyText = (level) => {
  const texts = {
    'beginner': '初学者',
    'intermediate': '中级',
    'advanced': '高级'
  }
  return texts[level] || level
}

const viewKnowledgePoints = (category) => {
  console.log('点击技术方向:', category.categoryName)
  router.push({
    path: '/questions/knowledge',
    query: {
      categoryId: category.id,
      categoryKey: category.categoryKey,
      categoryName: category.categoryName
    }
  }).then(() => {
    console.log('跳转成功！')
  }).catch(error => {
    console.error('跳转失败:', error)
  })
}

const addNewCategory = () => {
  isEdit.value = false
  dialogVisible.value = true
}

const editCategory = (category) => {
  isEdit.value = true
  Object.assign(categoryForm, category)
  dialogVisible.value = true
}

//禁用
const toggleStatus = async (category) => {
  try {
    const action = category.isActive ? '禁用' : '启用'
    await ElMessageBox.confirm(`确认${action}技术方向 "${category.categoryName}" 吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
    const updateData = {
      id:category.id,
      isActive:category.isActive?0:1
    }
    post('/umsAdmin/toggleCategoryStatus',updateData,content=>{
      category.isActive = updateData.isActive
      ElMessage.success(`${action}成功`)
    })
    
  } catch {
    // 用户取消操作
  }
}


//删除操作
const deleteCategory = async (category) => {
  try {
    await ElMessageBox.confirm(`确认删除技术方向 "${category.categoryName}" 吗？`, '警告', {
      type: 'error',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
    post('/umsAdmin/deleteCategoryLogic',{id:category.id},content=>{
      const index = techCategories.value.findIndex(item => item.id === category.id)
      if (index > -1) {
        techCategories.value.splice(index, 1)
        ElMessage.success('删除成功')
      }
    })
    
  } catch {
    // 用户取消操作
  }
}

//编辑和添加
const handleSubmit = async () => {
  try {
    submitLoading.value = true
    
    if (isEdit.value) {
      const formData = { ...categoryForm }
      post('/umsAdmin/updateCategory',formData,content=>{
      ElMessage.success('编辑成功')
      fetchTechCategories()
      })
    } else {
      const { id, ...newCategory } = categoryForm
      post('/umsAdmin/addCategory',newCategory,content=>{
        ElMessage.success('添加成功')
        fetchTechCategories()
      })
    }
    dialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const resetForm = () => {
  Object.assign(categoryForm, {
    id: null,
    categoryKey: '',
    categoryName: '',
    icon: '',
    color: '#409eff',
    description: '',
    difficultyLevel: 'beginner',
    estimatedDuration: '',
    orderNum: 0,
    isActive: 1,
    isDeleted: 0
  })
  formRef.value?.clearValidate()
}

const refreshData = () => {
  ElMessage.success('数据刷新成功')
  // 这里可以添加实际的数据刷新逻辑
}

onMounted(() => {
  // 组件挂载时的初始化逻辑
  console.log('技术方向管理页面初始化完成')
})
</script>

<style scoped>
.tech-category-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.category-card {
  min-height: 200px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 12px;
}

.category-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.card-disabled {
  opacity: 0.6;
}

.card-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
}

.card-icon {
  font-size: 40px;
  text-align: center;
  margin-bottom: 15px;
}

.card-info {
  flex: 1;
}

.category-title {
  margin: 0 0 10px 0;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  text-align: center;
}

.category-desc {
  margin: 0 0 15px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
  text-align: center;
}

.category-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
  margin-bottom: 15px;
}

.card-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.add-card {
  border: 2px dashed #dcdfe6;
  background: #fafafa;
}

.add-card:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.add-card-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
}

.add-card-content:hover {
  color: #409eff;
}

.add-icon {
  margin-bottom: 10px;
}

.add-card-content h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
}

.add-card-content p {
  margin: 0;
  font-size: 14px;
}

.icon-preview {
  margin-top: 8px;
  font-size: 14px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .category-grid {
    grid-template-columns: 1fr;
  }
  
  .tech-category-container {
    padding: 10px;
  }
}
</style>
